package com.hello.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hello.sky.constant.JwtClaimsConstant;
import com.hello.sky.constant.MessageConstant;
import com.hello.sky.constant.PasswordConstant;
import com.hello.sky.constant.StatusConstant;
import com.hello.sky.enmu.CommonError;
import com.hello.sky.exception.SkyException;
import com.hello.sky.mapper.EmployeeMapper;
import com.hello.sky.model.dto.EmployeeDTO;
import com.hello.sky.model.dto.PageParamDto;
import com.hello.sky.model.dto.PasswordEditDTO;
import com.hello.sky.model.entity.Employee;
import com.hello.sky.model.vo.EmployeeLoginVO;
import com.hello.sky.result.PageResult;
import com.hello.sky.result.Result;
import com.hello.sky.service.EmployeeService;
import com.hello.sky.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;

/**
 * <p>
 * 员工信息 服务实现类
 * </p>
 *
 * @author D
 */
@Slf4j
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Result login(Employee employee) {
        //查询用户
        Employee emp = baseMapper.getByUsername(employee.getUsername());

        //判断是否存在
        if (emp == null) throw SkyException.cast(MessageConstant.ACCOUNT_NOT_FOUND);

        //判断是否被禁用
        if (emp.getStatus() == StatusConstant.DISABLE) throw SkyException.cast(MessageConstant.ACCOUNT_LOCKED);

        //判断密码
        String psw = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        if (!psw.equals(emp.getPassword())) throw SkyException.cast(MessageConstant.PASSWORD_ERROR);


        //生成Jwt令牌
        HashMap<Object, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, emp.getId());
        claims.put("name", emp.getName());
        claims.put("username", emp.getUsername());
        String jwt = JwtUtil.getJwt(claims);

        //封装VO数据返回
        EmployeeLoginVO loginVO = new EmployeeLoginVO();
        BeanUtils.copyProperties(emp, loginVO);
        loginVO.setToken(jwt);
        loginVO.setUserName(emp.getUsername());
        return Result.success(loginVO);
    }

    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        employeeMapper.editPassword(passwordEditDTO);
    }

    @Override
    public void updateStatusById(Integer status, Long id) {
        if (status > 1 || status < 0) {
            SkyException.cast("status只能是0或1");
        }
        employeeMapper.updateStatusById(status, id);
    }

    @Override
    public PageResult getPage(PageParamDto params) {
        LambdaQueryWrapper<Employee> qr = new LambdaQueryWrapper<>();
        if (StringUtils.hasLength(params.getName()))
            qr.like(Employee::getName, params.getName()).or().like(Employee::getId, params.getName());
        Page<Employee> page = page(new Page<Employee>(params.getPage(), params.getPageSize()), qr);
        return new PageResult(page.getTotal(), page.getRecords());
    }

    @Override
    public void addEmp(EmployeeDTO employeeDTO) {
        //1. 账号必须是唯一的
        //2. 手机号为合法的11位手机号码
        //if (!employeeDTO.getPhone().matches("/^1\\d{10}$|^(0\\d{2,3}-?|\\(0\\d{2,3}\\))?[1-9]\\d{4,7}(-\\d{1,8})?$/")) throw SkyException.cast(CommonError.PHONE_NUMBER_ILLEGAL);
        //3. 身份证号为合法的18位身份证号码
        //if (!employeeDTO.getId().toString().matches("/^[1-8][1-7]\\d{4}(?:19|20)\\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\\d|3[01])\\d{3}[\\dX]$/")) throw SkyException.cast(CommonError.ID_NUMBER_ILLEGAL);
        //4. 密码默认为123456
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        employee.setStatus(StatusConstant.ENABLE);
        employeeMapper.addEmp(employee);
    }

    @Override
    public Employee getEmpById(Long id) {
        return employeeMapper.getEmpById(id);
    }

    @Override
    public void updateEmp(Employee employee) {
        employeeMapper.updateEmp(employee);
    }
}
